﻿
//URL参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = decodeURI(window.location.search).substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return "";
}

//获取cookie
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]); return null;
}

function getCookies(name, key) {
    var values = "&" + getCookie(name);
    if (values != null) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
        var r = decodeURI(values).substr(1).match(reg);
        if (r != null)
            return trim(unescape(r[2]));
    }
    return "";
}

//设置cookies
function setCookie(name, value, Days) {
    if (Days == null) Days = 30; //设置Cookie有效时间
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}

//删除左右两端的空格
function trim(str) {
    if (str == null) return "";
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

//跳转页面
function toUrl(url) {
    window.location.href = url;
}

//接口的数据是否正常
function isJsonSuccess(json) {
    if (json.Code == jsonCode.NotFound) {
        Alert("接口未找到");
        return false;
    }
    if (json.Code != jsonCode.success) {
        Alert(json.Message);
        return false;
    }
    return true;
}

//是否是空集合
function isEmptyList(list) {
    if (list == null || list.length == 0) {
        $(".im-no-data").show();
        return true;
    }

    return false;
}

function isLogin() {
    if (loginConfig == null || loginConfig.fromUid < 1) {
        toUrl('login.html');
        return false;
    }
    return true;
}

//显示消息
function Alert(msg) {
    var tip = $(".js_tooltips");
    tip.html(msg)
    tip.show();
    setTimeout(function () {
        tip.hide();
        tip.html("");
    }, 3000);
}

//ajax请求
var $ajax = {
    get: function (url, callBack) {
        this.ajax(url, "", "GET", callBack);
    },
    post: function (url, param, callBack) {
        this.ajax(url, param, "POST", callBack);
    },
    ajax: function (url, paramet, method, callBack) {
        setTimeout(function () { $('.im-loading').show() }, 1);
        $.ajax({
            url: url,
            type: method,
            dataType: "json",
            data: encodeURI(paramet),
            success: function (json) {
                $('.im-loading').hide();
                callBack(json);
            },
            error: function (rs) {
                Alert("请求异常!");
            }
        })
    }
}

var QDChat = {
    api: imConfig.api,

    //会话列表
    SessionList: function (fromUid) {
        var url = this.formatUrl(this.api.sessionList, 'openid=' + loginConfig.fromUid + "&page=1");
        $ajax.get(url, function (res) {
            if (!isJsonSuccess(res)) return;

            imClient.connect(res.Data.FromUser.Id);

            if (!isEmptyList(res.Data.List))
                bindData.bindSessionList(res.Data.List, res.Data.FromUser);
        });
    },

    //单聊消息列表
    msgList: function (fromUid,toUid) {
        var url = this.formatUrl(this.api.msgList, 'fromuid=' + fromUid + "&touid=" + toUid);
        $ajax.get(url, function (res) {
            if (!isJsonSuccess(res)) return;
            
            bindData.setMsgUser(res.Data.FromUser, res.Data.ToUser);

            if (!isEmptyList(res.Data.List))
                bindData.bindMsgList(res.Data.List, res.Data.FromUser, res.Data.ToUser);        
        });
    },

    //发送单聊消息
    sendMsg: function (fromUid, toUid, msg, msgType) {
        var url = this.formatUrl(this.api.sendMsg);
        var param = 'fromuid=' + fromUid + "&touid=" + toUid + '&msg=' + msg + '&msgType=' + msgType;
        $ajax.post(url, param, function (res) {
            if (!isJsonSuccess(res) || isEmptyList(res.Data))
                return;

            var item = res.Data;
            var _item = { FromUid: item.FromUid, Msg: msg, SendTime: item.SendTime };
            //发送人: 显示会话
            bindData.appendSession(fromUid, toUid, msg, 1);
            //发送人: 显示聊天内容    
            bindData.appendMsg(_item, msgUser.fromUser, msgUser.toUser);
        });
    },
    formatUrl: function (path, param) {
        return (param == null || param == '') ?
            imConfig.apiDomain + path :
            imConfig.apiDomain + path + "?" + param;
    }
}

//绑定数据
var bindData = {
    //显示会话列表
    bindSessionList: function (list, fromUser) {
        var html = '';
        var totalCount = 0;
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            var time = timeUtil.toSubTime(timeUtil.toDate(item.SendTime), null);
            var avatar = item.Avatar;
            var countStyle = item.MsgCount > 0 ? '' : 'style="display:none"';
            html += '<div class="weui-cell a-session" data-fromuid="' + item.FromUid + '" data-touid="' + item.ToUid + '" data-time="" data-id="im_detail">'
            html += '<div class="weui-cell__hd" style="position: relative;margin-right: 10px;">'
            html += '<img src="' + avatar + '" class="session-avatar" />'
            html += '<span class="weui-badge session-count" ' + countStyle + '>' + item.MsgCount + '</span>'
            html += '</div>'
            html += '<div class="weui-cell__bd"><p class="session-name">' + item.NickName + '</p><p class="session-msg">' + item.LastMsg + '</p></div>'
            html += '<div class="weui-cell__ft session-time">' + time + '</div>'
            html += '</div>'
            totalCount += item.MsgCount;
        }
        $(".im-session-list").append(html);
        $(".im-totalcount").html(totalCount);
        if (totalCount > 0)
            $(".im-totalcount").show();
        bindSessionLink(fromUser);
    },
    //追加会话
    appendSession: function (fromUid, toUid, msg, countType) {
        var session = this.getSession(fromUid, toUid, msg, countType);
        //修改
        if (session != null) {
            var time = timeUtil.toSubTime(timeUtil.toTimestamp());
            session.find('.session-time').html(time);               //时间
            session.find('.session-msg').html(msg);                 //内容

            //累加未读数
            if (countType == 2) {
                var divCount = session.find('.session-count');          //未读数
                divCount.html(parseInt(divCount.html()) + 1);
                divCount.show();
            }
        }
        else {
            //增加    
            console.log("增加新会话");
        }    
    },

    //从列表中获取一个会话
    getSession: function (fromUid, toUid, msg, countType) {
        var session = null;
        $(".im-session-list").children().each(function () {
            var _fromUid = $(this).attr('data-fromuid');
            var _toUid = $(this).attr('data-touid');
            if ((_fromUid == fromUid && _toUid == toUid) ||
                (_fromUid == toUid && _toUid == fromUid)) {
                session = $(this);
            }
        });
        return session;
    },

    //显示消息列表
    bindMsgList: function (list,fromUser,toUser) {
        var html = '';
        for (var i = list.length - 1; i >= 0; i--) {
            var item = list[i];
            html += this.bindMsg(item, fromUser, toUser);
        }
        $(".im-msg-list").append(html);
        this.setBottom();
    },
    //显示一条聊天消息
    bindMsg: function (item, fromUser, toUser) {
        var type = item.FromUid == fromUser.Id ? 0 : 1;;
        var time = item.SendTime.substr(5, 11);
        var html = ''
        html += '<li class="pop__chat-msg-time"><span>' + time + '</span></li>';
        //发送的消息
        if (type == 0) {
            html += '<li class="pop__chat-msg-me" type="friend">'
            html += '   <div class="pop__chat-msg-content">'
            html += '       <div class="pop__chat-msg-msg pop__chat-msg-text"><span>' + item.Msg + '</span></div>'
            html += '   </div>'
            html += '   <span class="pop__chat-msg-avatar"><img src="' + fromUser.Avatar + '"></span>'
            html += '</li>'
        }
        //接收的消息
        if (type == 1) {
            html += '<li class="pop__chat-msg-others" type="friend">'
            html += '   <span class="pop__chat-msg-avatar"><img src="' + toUser.Avatar + '"></span>'
            html += '   <div class="pop__chat-msg-content"><div class="pop__chat-msg-msg pop__chat-msg-text"><span>' + item.Msg + '</span></div></div>'
            html += '</li>'
        }
        return html;
    },
    //设置聊天用户
    setMsgUser: function (fromUser, toUser) {
        var name = fromUser.OpenId == loginConfig.fromUid ?
            toUser.NickName :
            fromUser.NickName;
        $(".im-name").html(name);
        
        msgUser.fromUser.Id = fromUser.Id;
        msgUser.fromUser.NickName = fromUser.NickName;
        msgUser.fromUser.Avatar = fromUser.Avatar;

        msgUser.toUser.Id = toUser.Id;
        msgUser.toUser.NickName = toUser.NickName;
        msgUser.toUser.Avatar = toUser.Avatar;
    },

    //显示一条聊天消息
    appendMsg: function (item, fromUser, toUser) {     
        var html = this.bindMsg(item, fromUser, toUser);
        $(".im-msg-list").append(html);
        this.setBottom();
    },
    //聊天对话置底
    setBottom: function () {
        var href = document.location.href;
        if (href.indexOf("#im_detail") == -1) return;
        setTimeout(function () {
            var div = document.getElementById('chat-box');
            div.scrollTop = div.scrollHeight;
        }, 100)
    }

    //底部总未读数
    , bindTotalCount: function (appendCount) {
        var totalCount = appendCount;
        $(".im-session-list").children().each(function () {
            var count = $(this).find(".session-count").html();           
            if (count != null) 
                totalCount += parseInt(count);
        });
        $(".im-totalcount").html(totalCount);
        if (totalCount > 0)
            $(".im-totalcount").show();
        else
            $(".im-totalcount").hide();
    }
}

//对话的用户
var msgUser = {
    toUser: { Id: 0, NickName: '', Avatar: '' },
    fromUser: { Id: 0, NickName: '', Avatar: '' },

    reset: function () {
        this.toUser = { Id: 0, NickName: '', Avatar: '' }
        this.fromUser = { Id: 0, NickName: '', Avatar: '' }
    }
}

var imClient = {
    ws: null,
    connect: function (from_uid) {
        // 假设服务端ip为127.0.0.1
        ws = new WebSocket(imConfig.imDomain);
        ws.onmessage = imClient.onMessage;
        ws.onerror = imClient.onerror;
        ws.onclose = imClient.onclose;
        ws.onopen = function (e) {
            console.log("连接成功");
            imClient.send({ "type": "connect", "from_uid": from_uid });
        };
    },
    onerror:function(e){
        console.log("imClient 出现错误");
    },
    onclose: function (e) {
        console.log("连接关闭，定时重连");
    },
    sendMsg: function (from_uid, to_uid, content) {
        var msg = { "type": "send", "from_uid": from_uid, "to_uid": to_uid, "content": content };
        this.send(msg);
    },
    send: function (msgObj) {
        var msg = JSON.stringify(msgObj);
        //console.log('发送:' + msg)
        ws.send(msg);
    },
    onMessage: function (e) {
        console.log("收到消息：" + e.data);
        var json = JSON.parse(e.data);

        if (json.type == 'send') {
            var _item = { FromUid: json.from_uid, Msg: json.content, SendTime: timeUtil.toDate(timeUtil.toTimestamp()) };

            //接收人：显示会话
            bindData.appendSession(json.from_uid, json.to_uid, json.content, 2);  //更新会话
            //接收人: 显示聊天内容 
            bindData.appendMsg(_item, msgUser.fromUser, msgUser.toUser);
            bindData.bindTotalCount(0);
        }
    }
}

//日期工具
var timeUtil = {
    toTimestamp: function (date) {
        //date格式：2017-12-08 20:5:30
        var now = date == null ? new Date() : new Date(t);
        return now.getTime();
    },
    toDate: function (timestamp) {
        var date = new Date(timestamp * 1000);  //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        Y = date.getFullYear();
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        D = date.getDate() < 10 ? '0' + date.getDate() : +date.getDate();
        h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
        m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
    },
    toSubTime: function (startTime) {
        //var date1 = '2015/05/01 00:00:00';  //开始时间          
        var date1 = startTime;
        var date2 = new Date();    //结束时间  
        var date3 = date2.getTime() - new Date(date1).getTime();   //时间差的毫秒数        
        //var days = Math.floor(date3 / (24 * 3600 * 1000))         //相差天数

        var totalMinutes = Math.floor(date3 / (60 * 1000));
        if (totalMinutes < 1)
            return "1分钟前";
        else if (totalMinutes < 60)
            return totalMinutes + "分钟前";
        else if ((totalMinutes / 60) <= 2)
            return Math.round(totalMinutes / 60) + "小时前";
        else
            return startTime.substr(5, 11);
    }
}

function bindSessionLink(fromUser) {
    //单聊链接
    $('.a-session').on('click', function () {
        var fromUid = $(this).attr("data-fromuid");     //发送人
        var toUid = $(this).attr('data-touid');         //接收人
        var id = $(this).data('id');
        window.pageManager.go(id);
        if (fromUser.Id == fromUid)
            QDChat.msgList(fromUser.Id, toUid);
        else
            QDChat.msgList(fromUser.Id, fromUid);

        var count = $(this).find(".session-count").html();
        
        //清空未读数
        $(this).find(".session-count").html("0");
        $(this).find(".session-count").hide();
        bindData.bindTotalCount(parseInt(count));
    });
}